package com.xuerhua.yxt.wechat.utils;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.xuerhua.yxt.baidu.model.AipFaceDetect;
import com.xuerhua.yxt.common.Const;
import com.xuerhua.yxt.common.WechatConfigure;
import com.xuerhua.yxt.common.enums.FileType;
import com.xuerhua.yxt.common.enums.MimeType;
import com.xuerhua.yxt.common.enums.RelationType;
import com.xuerhua.yxt.common.enums.Status;
import com.xuerhua.yxt.utils.DateUtil;
import com.xuerhua.yxt.utils.FileUtils;
import com.xuerhua.yxt.utils.TextUtil;
import com.xuerhua.yxt.wechat.message.InputMessage;
import com.xuerhua.yxt.wechat.model.WechatUserInfo;

@SuppressWarnings("restriction")
public class FileUtil {
	
	private static Logger logger = LoggerFactory.getLogger(FileUtil.class);
	
	/**
	 * 下载用户微信头像
	 * @param openid
	 * @return
	 */
	public static String uploadHeadImg(String openid) {
		WechatUserInfo userInfo = WechatUtils.getUserInfo(WechatUtils.getWechatModel().getAccessToken(), openid);
		return FileUtils.writeHttpFile(userInfo.getHeadimgurl(), RelationType.HEAD_IMG_URL.getCode());
	}
	
	/**
	 * 下载微信公众号上传的文件
	 * @auther 胡启萌
	 * @Date 2017年4月7日
	 * @param path 文件保存路径
	 * @param message 消息信息
	 * @param isThumb 是否是缩略图
	 */
	public static String downloadWechatFile(InputMessage message, String relationType, Boolean isThumb) {
		try {
			String mediaId = isThumb ? message.getThumbMediaId() : message.getMediaId();
			String wechatUrl = TextUtil.format(WechatConfigure.getInstance().getMediaDownload(), 
					new String[]{WechatUtils.getAccessToken(), mediaId});
			URL url = new URL(wechatUrl);
    		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    		conn.setRequestMethod("GET");
    		conn.setDoInput(true);
    		String suffix = MimeType.getKey(conn.getContentType());
     		String fileName = mediaId + "." + suffix;
    		String relationPath = relationType + File.separator + DateUtil.dateToStr(new Date(), DateUtil.DATE_YM_FORMAT);
    		// 文件保存磁盘的完整路径
            String attachmentURL = Const.rootPath + File.separator + relationPath;
            createDir(attachmentURL);
            relationPath += File.separator + fileName;
            attachmentURL += File.separator + fileName;
            Boolean isImageReduce = false;
            BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
            if(message.getMsgType().equals(FileType.IMAGE.getCode())) {
            	BufferedImage sourceImg =  javax.imageio.ImageIO.read(bis);
            	if(sourceImg.getWidth() > 1280) {//压缩图片
            		isImageReduce = true;
            		int height = new BigDecimal(1280).divide(new BigDecimal(sourceImg.getWidth()), BigDecimal.ROUND_FLOOR, 2).multiply(new BigDecimal(sourceImg.getHeight())).intValue();
                	reduceImg(sourceImg, attachmentURL, 1280, height);
                }
            	if(!isImageReduce) {
            		FileOutputStream fos = new FileOutputStream(new File(attachmentURL)); 
            		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);        
        	        encoder.encode(sourceImg);        
        	        fos.close();
            	}
            }else {
            	FileOutputStream fos = new FileOutputStream(new File(attachmentURL));  
                byte[] buf = new byte[8096];  
                int size = 0;  
                while ((size = bis.read(buf)) != -1)  
                    fos.write(buf, 0, size);  
                fos.close();  
            }
            bis.close();
            conn.disconnect();
            return relationPath;
		} catch (Exception e) {
			logger.error("创建文件路径出错, error={}", e);
		}
		return null;
    }
	
	public static AipFaceDetect saveFaceImg(String base64, String fileDir, String fileName) {
		AipFaceDetect faceDetect = new AipFaceDetect();
		try {
    		// 文件保存磁盘的完整路径
            String attachmentURL = Const.rootPath + File.separator + fileDir;
            createDir(attachmentURL);
            String relationPath = fileDir + File.separator + fileName;
            attachmentURL += File.separator + fileName;
    		File imageFile = new File(attachmentURL);  
	        // 创建输出流  
	        FileOutputStream outputStream = new FileOutputStream(imageFile);  
	        // 获得一个图片文件流，我这里是从flex中传过来的  
	        byte[] result = Base64.decodeBase64(base64);//解码  
	        for (int i = 0; i < result.length; ++i) {  
	            if (result[i] < 0) {// 调整异常数据  
	            	result[i] += 256;
	            }
	        }  
	        outputStream.write(result);  
	        outputStream.flush();   
	        outputStream.close();
	        
            relationPath = relationPath.replaceAll("\\\\", "/");
            faceDetect.setFileUrl(relationPath);
            faceDetect.setError_code("0");
            return faceDetect;
		} catch (Exception e) {
			logger.error("人脸上传异常, error={}", e);
			faceDetect.setError_code(Status.FAIL.getCode());
			faceDetect.setError_msg("人脸上传异常");
		}
		return faceDetect;
    }
	
	private static ByteArrayOutputStream cloneInputStream(InputStream input) {
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len;
			while ((len = input.read(buffer)) > -1) {
				baos.write(buffer, 0, len);
			}
			baos.flush();
			input.close();
			return baos;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static String wxuploadImage(String mediaId, String relationType) {
		try {
			String wechatUrl = TextUtil.format(WechatConfigure.getInstance().getMediaDownload(), 
					new String[]{WechatUtils.getAccessToken(), mediaId});
			URL url = new URL(wechatUrl);
    		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    		conn.setRequestMethod("GET");
    		conn.setDoInput(true);
    		String suffix = MimeType.getKey(conn.getContentType());
     		String fileName = mediaId + "." + suffix;
    		String relationPath = relationType + File.separator + DateUtil.dateToStr(new Date(), DateUtil.DATE_YM_FORMAT);
    		// 文件保存磁盘的完整路径
            String attachmentURL = Const.rootPath + File.separator + relationPath;
            createDir(attachmentURL);
            relationPath += File.separator + fileName;
            attachmentURL += File.separator + fileName;
            BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
            BufferedImage sourceImg =  javax.imageio.ImageIO.read(bis);
    		int height = new BigDecimal(1080).divide(new BigDecimal(sourceImg.getWidth()), BigDecimal.ROUND_FLOOR, 2).multiply(new BigDecimal(sourceImg.getHeight())).intValue();
        	reduceImg(sourceImg, attachmentURL, 1080, height);
        	FileOutputStream fos = new FileOutputStream(new File(attachmentURL)); 
    		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);        
	        encoder.encode(sourceImg);        
	        fos.flush();
	        fos.close();
            bis.close();
            conn.disconnect();
            relationPath = relationPath.replaceAll("\\\\", "/");
 	       return relationPath;
		} catch (Exception e) {
			logger.error("创建文件路径出错, error={}", e);
		}
		return null;
    }
	
	public static void reduceImg(Image src, String imgsrc, int widthdist, int heightdist) {
		try {        
			File srcfile = new File(imgsrc);        
	        if (!srcfile.exists()) {        
	            srcfile.createNewFile();     
	        }  
	        BufferedImage tag= new BufferedImage(widthdist, heightdist, BufferedImage.TYPE_INT_RGB);        
	        tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist,  Image.SCALE_SMOOTH), 0, 0,  null);        
	        FileOutputStream out = new FileOutputStream(srcfile);  
	        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);        
	        encoder.encode(tag);        
	        out.close();
	    } catch (IOException ex) {        
	        ex.printStackTrace();        
	    }   
	}
	
	public static void createDir(String uploadPath) {
        File file = new File(uploadPath);
        // 如果该文件目录不存在，则创建一个新的目录
        if (!file.exists()) {
            file.mkdirs();
        }
    }
	
	public static void main(String[] args) {
		String contentType = "image/jpeg";
		if(contentType.indexOf(";") != -1) {
			contentType = contentType.substring(0, contentType.indexOf(";"));
		}
		String extName = MimeType.getKey(contentType);
		System.out.println(extName);
	}
}
